<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="scId">
        <el-select v-model="queryParams.scId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="storeCenter in StoreCenterInfoList" :key="storeCenter.id" :value="storeCenter.id" :label="storeCenter.name">{{storeCenter.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId" >
        <el-select v-model="queryParams.supplierId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="supplier in SupplierList" :key="supplier.id" :value="supplier.id" :label="supplier.name">{{supplier.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购员" prop="purchaserId" >
        <el-select v-model="queryParams.purchaserId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.userId" :label="user.userName">{{user.userName}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.userId" :label="user.userName">{{user.userName}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy">
        <el-select v-model="queryParams.approveBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.userId" :label="user.userName">{{user.userName}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime">
        <el-date-picker clearable
          v-model="queryParams.approveTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" @keyup.enter.native="handleQuery">
          <el-option value="0" label="待审核">待审核</el-option>
          <el-option value="3" label="审核通过">审核通过</el-option>
          <el-option value="6" label="审核拒绝">审核拒绝</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货订单号" prop="receiveSheetId" label-width="100px">
        <el-input
          v-model="queryParams.receiveSheetId"
          placeholder="请输入收货订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算状态" prop="settleStatus">
        <el-select v-model="queryParams.settleStatus" @keyup.enter.native="handleQuery">
          <el-option value="0" label="未结算">未结算</el-option>
          <el-option value="1" label="已结算">结算中</el-option>
          <el-option value="3" label="已结算">已结算</el-option>
          <el-option value="6" label="已结算">无需结算</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['PurchaseReturn:save']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:PurchaseReturn:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PurchaseReturnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
<!--      <el-table-column label="ID" align="center" prop="id"  width="200px"/>-->
      <el-table-column label="单据号" align="left" prop="code"  width="200px"/>

      <el-table-column label="关联订单编号" align="left" prop="tblPurchaseOrder.code"  width="200px" />

      <el-table-column label="仓库名称" align="left" prop="scName"   width="100px"/>
      <el-table-column label="供应商名称" align="left" prop="supplierName"  width="100px" />
      <el-table-column label="采购员" align="left" prop="purchaserName"  width="100px" />
      <el-table-column label="单据金额" align="left" prop="tblPurchaseOrder.totalAmount"  width="100px" >
        <template slot-scope="scope">
          <span>{{Number(scope.row.tblPurchaseOrder.totalAmount).toLocaleString('en-US') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="left" prop="tblPurchaseOrder.totalNum"  width="100px" />
      <el-table-column label="操作时间" align="left" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="left" prop="createBy"  width="100px" />
      <el-table-column label="状态" align="left" prop="status" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">待审核</span>
          <span v-if="scope.row.status == 3">审核通过</span>
          <span v-if="scope.row.status == 6">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="left" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="left" prop="approveBy"  width="100px" />
      <el-table-column label="结算状态" align="left" prop="settleStatus" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.settleStatus == 0">未结算</span>
          <span v-if="scope.row.settleStatus == 1">结算中</span>
          <span v-if="scope.row.settleStatus == 2">已结算</span>
          <span v-if="scope.row.settleStatus == 6">无需结算</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="description"  width="100px" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="selectPurchaseReturn(scope.row)"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['PurchaseReturn:save']"
          >修改</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="statusUpdate(scope.row)"
            v-hasPermi="['system:admin:query']"
          >审批</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:PurchaseReturn:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看按钮 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>仓库：{{ this.form.scName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>供应商：{{ this.form.supplierName }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>采购员：{{ this.form.purchaserName }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>付款日期：{{ this.form.paymentDate }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>采购单据号：{{ this.form.tblPurchaseOrder.code }}</p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>状态：<span :style="{color: statusColor}">{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ this.form.createTime }}</p></div>
<!--        <br>-->
<!--        <div style="display: inline-block;width: 300px;"><p>审核人：{{ this.form.approveBy }}</p></div>-->
<!--        <div style="display: inline-block;width: 300px;"><p>审核时间：{{ this.form.approveTime }}</p></div>-->
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="this.tblPurchaseReturnDetailList" @selection-change="handleSelectionChange">
          <!--        商品数据-->
          <el-table-column label="商品编号" align="left" prop="productInfo.code" width="200px" v-if="purchaseType===0"/>
          <el-table-column label="商品名称" align="left" prop="productInfo.name" width="200px" v-if="purchaseType===0"/>
          <el-table-column label="单位" align="left" prop="productInfo.unit" width="100px" v-if="purchaseType===0"/>
          <el-table-column label="规格" align="left" prop="productInfo.spec" width="100px" v-if="purchaseType===0"/>
          <el-table-column label="商品类目" align="left" prop="productInfo.baseDataProductCategory.name" width="100px" v-if="purchaseType===0"/>
          <el-table-column label="商品品牌" align="left" prop="productInfo.baseDataProductBrand.name" width="100px" v-if="purchaseType===0"/>

          <!--        物料数据-->
          <el-table-column label="物料编号" align="left" prop="material.materialCode" width="200px" v-if="purchaseType===1"/>
          <el-table-column label="物料名称" align="left" prop="material.materialName" width="150px" v-if="purchaseType===1"/>
          <el-table-column label="物料类型" align="left" prop="material.typeName" width="100px" v-if="purchaseType===1"/>
          <el-table-column label="规格型号" align="left" prop="material.specification" width="150px" v-if="purchaseType===1"/>
          <el-table-column label="分类名称" align="left" prop="material.categoryName" width="100px" v-if="purchaseType===1"/>
          <el-table-column label="单位" align="left" prop="material.purchaseUnitName" width="100px" v-if="purchaseType===1"/>

          <el-table-column label="收货数量" align="left" prop="tblPurchaseOrderDetail.receiveNum" width="100"/>
          <el-table-column label="剩余退货数量" align="left" prop="" width="100">
            <template slot-scope="scope">
              <span>{{scope.row.tblPurchaseOrderDetail.orderNum - scope.row.tblPurchaseOrderDetail.returnNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退货数量" align="left" prop="returnNum" width="100"/>
          <el-table-column label="备注" align="left" prop="description" width="100px"/>
        </el-table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
        <label >备注： </label>
        <textarea style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid" v-model="this.form.description" disabled/>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm()" v-if="this.title == '查看采购订单'">打 印</el-button>
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批采购订单'">审批通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批采购订单'&&this.form.status!=6">审批拒绝</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog :title="title" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="statusCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPurchaseReturn, getPurchaseReturn, delPurchaseReturn, addPurchaseReturn, updatePurchaseReturn } from "@/api/system/PurchaseReturn";
import {listSettlePreSheet,addSettlePreSheet} from "@/api/system/SettlePreSheet";
import { listUser} from "@/api/system/user";
import {listSupplier} from "@/api/system/Supplier";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import {listReceiveSheet, updateReceiveSheet} from "@/api/system/ReceiveSheet";
import {listStock} from "@/api/system/stock";
import {listLog,addLog} from "../../../api/system/log";
import {addSettleFeeSheet, listSettleFeeSheet} from "@/api/system/SettleFeeSheet";
import SettleFeeSheet from "@/views/system/SettleFeeSheet/index.vue";
import {listMaterialStock} from "@/api/system/MaterialStock";


export default {
  name: "PurchaseReturn",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购退单表格数据
      PurchaseReturnList: [],
      // 采购退单明细表格数据
      tblPurchaseReturnDetailList: [],

      PurchaseReturnByOrderIdList: [],
      // 退货数量
      returnNum: 0,
      //商品数量
      orderNum:0,
      // 赠品数量
      giftNum: 0,
      // 含税总金额
      taxAmount: 0,

      //用户列表
      UserList: [],
      // 供应商列表
      SupplierList: [],
      //仓库列表
      StoreCenterInfoList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拒绝原因弹窗
      refuseOpen:false,
      //弹窗状态颜色
      statusColor:"rgb(100, 100, 100)",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        receiveSheetId: null,
        createById: null,
        approveBy: null,
        approveTime: null,
        status: null,
        settleStatus: null,
      },
      returnQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        receiveSheetId: null,
        createById: null,
        approveBy: null,
        approveTime: null,
        status: null,
        settleStatus: null,
      },
      // 表单参数
      form: {
        tblPurchaseOrder:{
          code: null,
        }
      },

      //拒绝原因
      refuseForm: {
        reason: ''
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },
      //商品库存记录的id列表
      stockLogList:[],

      //供应商应付款
      SettleFeeSheet:[],
      SettleFeeSheet2:[],
      supplierSettleFeeSheetDetail:[],

      //采购收货数据
      ReceiveSheetList:[],

      //详情类型
      purchaseType:0,
    };
  },
  created() {
    this.getList();
    this.getUserList();
    this.getSupplierList();
    this.getSupplierListId();
    this.getStoreCenterInfoList();
    this.selectStockLogList();
    this.selectSupplierSettleFeeSheet();
  },
  methods: {
    //商品库存变动记录
    selectStockLogList(){
      listLog({}).then(response => {
        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.stockLogList.push(list[i].id)
        }
      });
    },

    /** 查询采购收货单列表 */
    async getReceiveSheetList(id) {
      listReceiveSheet({purchaseOrderId:id}).then(response => {
        this.ReceiveSheetList = response.rows;
      });
    },

    //供应商应收款
    selectSupplierSettleFeeSheet(){
      listSettleFeeSheet({}).then(response => {
        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.supplierSettleFeeSheetDetail.push(list[i].id)
        }
      });
    },
    /** 查询采购退单列表 */
    getList() {
      this.loading = true;

      let name=this.$store.state.user.name

      listPurchaseReturn(this.queryParams).then(response => {
        this.PurchaseReturnList = [];
        let list= response.rows;

        if (name!="admin"){
          for (let i = 0; i < list.length; i++) {
            console.log(list[i].purchaserName);
            if (list[i].purchaserName == name){
              this.PurchaseReturnList.push(list[i])
            }
          }
        }else {
          this.PurchaseReturnList = list;
        }

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询供应商应收款单列表 */
    getSupplierListId() {
      this.SettleFeeSheet=[];
      var list=[];
      listSettleFeeSheet({}).then(response => {
        this.SettleFeeSheet2=response.rows;
        list=response.rows;
        for (var i=0;i<list.length;i++){
          this.SettleFeeSheet.push(list[i].id);
        }
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        this.SupplierList = response.rows;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.queryParams={}
      this.getList();
    },

    // 审核拒绝取消按钮
    statusCancel() {
      this.refuseOpen=false;
      this.open=true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        scId: null,
        supplierId: null,
        purchaserId: null,
        paymentDate: null,
        purchaseOrderId: null,
        totalNum: null,
        totalGiftNum: null,
        totalAmount: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        status: null,
        refuseReason: null,
        settleStatus: null,
        txId: null,
        oriSettleStatus: null,
        tblPurchaseOrder: {
          code: null,
        }
      };
      this.tblPurchaseReturnDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path:'/PurchaseReturn/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.$router.push({
        path:'/PurchaseReturn/update',
        query:{
          id: id,
        }
      })
    },

    //根据订单ID查询关联退货数据
    async selectReturnByOrderId(id){
      this.PurchaseReturnByOrderIdList=[]
      this.returnQueryParams={
        purchaseOrderId:id,
        status: 3
      }
      listPurchaseReturn(this.returnQueryParams).then(response => {
        this.PurchaseReturnByOrderIdList = response.rows;
      });
    },

    /** 提交按钮 */
    async submitForm(status) {
      if (status==6){
        this.open = false;
        this.refuseOpen=true
      }else {
        if (this.formInfo()){

          let list=[];
          let stockNumList=[];

          for (let i = 0; i < this.form.tblPurchaseReturnDetailList.length; i++) {
            let orderReturn=this.form.tblPurchaseReturnDetailList[i].tblPurchaseOrderDetail.returnNum;    //订单退货数量
            let receiveReturn=0;     //收货中已入库的退货数量
            let returnNum=0;    //审核通过的退货数量

            //获取收货中已入库的退货数量
            for (let j = 0; j < this.ReceiveSheetList.length; j++) {
              if (this.ReceiveSheetList[j].status==3){
                for (let k = 0; k < this.ReceiveSheetList[j].tblReceiveSheetDetailList.length; k++) {
                  if (this.ReceiveSheetList[j].tblReceiveSheetDetailList[k].purchaseOrderDetailId==this.form.tblPurchaseReturnDetailList[i].purchaseOrderDetailId){
                    receiveReturn+=this.ReceiveSheetList[j].tblReceiveSheetDetailList[k].returnNum;
                  }
                }
              }
            }

            //获取退货审核通过的退货数量
            for (let j = 0; j < this.PurchaseReturnByOrderIdList.length; j++) {
              for (let k = 0; k < this.PurchaseReturnByOrderIdList[j].tblPurchaseReturnDetailList.length; k++) {
                if (this.PurchaseReturnByOrderIdList[j].tblPurchaseReturnDetailList[k].purchaseOrderDetailId==this.form.tblPurchaseReturnDetailList[i].purchaseOrderDetailId){
                  returnNum+=this.PurchaseReturnByOrderIdList[j].tblPurchaseReturnDetailList[i].returnNum;
                }
              }
            }

            if (this.purchaseType==0){
              const stock = await this.getProductStock(
                this.form.scId,
                this.form.tblPurchaseReturnDetailList[i].productId
              );

              if (stock) {
                stockNumList.push({id:this.form.tblPurchaseReturnDetailList[i].id,stockNum:stock.stockNum})
                let outStockNum=0;

                //判断未入库的商品是否退完
                if (returnNum<orderReturn-receiveReturn){
                  //判断当前退货数是否大于还可退的未入库商品数
                  //如果为true，则将当前退货数减去还可退的未入库商品数得到本次需要出库的商品数量
                  if (this.form.tblPurchaseReturnDetailList[i].returnNum>(orderReturn-receiveReturn-returnNum)){
                    outStockNum=this.form.tblPurchaseReturnDetailList[i].returnNum-(orderReturn-receiveReturn-returnNum)
                  }
                }else {
                  outStockNum=this.form.tblPurchaseReturnDetailList[i].returnNum;
                }

                let stockNum=parseInt(stock.stockNum);
                stock.stockNum=stockNum-outStockNum;
                let taxAmount=stock.taxAmount-(this.form.tblPurchaseReturnDetailList[i].taxPrice*outStockNum);
                stock.taxAmount=taxAmount;
                this.form.tblPurchaseReturnDetailList[i].productInfo.tblProductStock = stock;

                if (stock.stockNum<0){
                  this.$modal.msgError(this.form.tblPurchaseReturnDetailList[i].productInfo.name+"的库存数量不足以完成此次退货操作");
                  return
                }

                list.push({id: this.form.tblPurchaseReturnDetailList[i].id,outStockNum:outStockNum});
              }else {
                this.form.tblPurchaseReturnDetailList[i].baseDataProduct.tblProductStock = {
                  id: generateUniqueId(this.productStockAllList),
                  scId: this.form.scId,
                  productId: this.form.tblPurchaseReturnDetailList[i].productId,
                  stockNum: Number(this.form.tblPurchaseReturnDetailList[i].receiveNum)-Number(this.form.tblPurchaseReturnDetailList[i].returnNum),
                  taxPrice: this.form.tblPurchaseReturnDetailList[i].taxPrice,
                  taxAmount: this.form.tblPurchaseReturnDetailList[i].taxPrice*(Number(this.form.tblPurchaseReturnDetailList[i].receiveNum)-Number(this.form.tblPurchaseReturnDetailList[i].returnNum)),
                };
              }
            }else {
              const stock = await this.getMaterialStock(
                this.form.scId,
                this.form.tblPurchaseReturnDetailList[i].materialId
              );

              if (stock) {
                let outStockNum=0;

                //判断未入库的商品是否退完
                if (returnNum<orderReturn-receiveReturn){
                  //判断当前退货数是否大于还可退的未入库商品数
                  //如果为true，则将当前退货数减去还可退的未入库商品数得到本次需要出库的商品数量
                  if (this.form.tblPurchaseReturnDetailList[i].returnNum>(orderReturn-receiveReturn-returnNum)){
                    outStockNum=this.form.tblPurchaseReturnDetailList[i].returnNum-(orderReturn-receiveReturn-returnNum)
                  }
                }else {
                  outStockNum=this.form.tblPurchaseReturnDetailList[i].returnNum;
                }

                let stockQuantity=parseInt(stock.stockQuantity);
                stock.stockQuantity=stockQuantity-outStockNum;
                this.form.tblPurchaseReturnDetailList[i].material.materialStock = stock;

                if (stock.stockQuantity<0){
                  this.$modal.msgError(this.form.tblPurchaseReturnDetailList[i].material.materialName+"的库存数量不足以完成此次退货操作");
                  return
                }

                list.push({id: this.form.tblPurchaseReturnDetailList[i].id,outStockNum:outStockNum});
              }else {
                this.form.tblPurchaseReturnDetailList[i].material.materialStock = {
                  id: generateUniqueId(this.productStockAllList),
                  warehouseId: this.form.scId,
                  warehouseName:this.form.scName,
                  materialId: this.form.tblPurchaseReturnDetailList[i].materialId,
                  materialCode: this.form.tblPurchaseReturnDetailList[i].material.materialCode,
                  materialName: this.form.tblPurchaseReturnDetailList[i].material.materialName,
                  stockQuantity: Number(this.form.tblPurchaseReturnDetailList[i].receiveNum)-Number(this.form.tblPurchaseReturnDetailList[i].returnNum),
                  lastInTime: new Date(),
                  remark: this.form.tblPurchaseReturnDetailList[i].remark,
                };
              }
            }
          }
          this.form.status=status;
          this.form.approveBy='系统管理员';
          this.form.approveTime=new Date();

          updatePurchaseReturn(this.form).then(response => {
            this.$modal.msgSuccess("审批成功");

            if (this.purchaseType==0){
              let stockNums = 0;

              //商品库存变动记录
              for (let i = 0; i < this.form.tblPurchaseReturnDetailList.length; i++) {

                for (let j = 0; j < stockNumList.length; j++) {
                  if (stockNumList[j].id===this.form.tblPurchaseReturnDetailList[i].id){
                    stockNums=stockNumList[j].stockNum;
                    break
                  }
                }

                for (let j = 0; j < list.length; j++) {
                  if (this.form.tblPurchaseReturnDetailList[i].id === list[j].id){
                    if (list[j].outStockNum>0){
                      let stockNum = 0-list[j].outStockNum;
                      let taxAmount = stockNum*this.form.tblPurchaseReturnDetailList[i].taxPrice;
                      let stockLog = {
                        id: generateUniqueId(this.stockLogList),
                        scId: this.form.scId,
                        productId: this.form.tblPurchaseReturnDetailList[i].productId,
                        oriTaxPrice: this.form.tblPurchaseReturnDetailList[i].productInfo.tblProductStock.taxPrice,
                        curTaxPrice: this.form.tblPurchaseReturnDetailList[i].taxPrice,
                        oriStockNum: stockNums,
                        curStockNum: stockNums - list[j].outStockNum,
                        stockNum: stockNum,
                        taxAmount: taxAmount,
                        createBy: '系统管理员',
                        createById: '1',
                        createTime: new Date(),
                        bizCode: this.form.code,
                        bizType: 2,
                      }
                      addLog(stockLog).then(response => {
                      })
                    }
                  }
                }
              }
            }

            //新增一条供应商应付款信息
            const newId = generateUniqueId(this.SettleFeeSheet);
            const Code = getOrderCode(this.SettleFeeSheet2);
            let supplierSettleFeeSheet = {
              id: newId,
              code: Code,
              supplierId: this.form.supplierId,
              totalAmount: this.form.totalAmount,
              sheetType: 1,
              status: 0,
              settleFeeSheetDetailList:[{
                id: generateUniqueId(this.supplierSettleFeeSheetDetail),
                orderId: this.form.id,
                sheetId: newId,
                amount: this.form.totalAmount,
              }],
              createBy: '系统管理员',
              createById: '1',
            }
            addSettleFeeSheet(supplierSettleFeeSheet).then(response => {
            });
            this.open = false;

            this.queryParams={}
            this.getList();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      for (var i = 0; i < this.tblPurchaseReturnDetailList.length; i++) {
        if (this.tblPurchaseReturnDetailList[i].tblPurchaseOrderDetail.returnNum>this.tblPurchaseReturnDetailList[i].tblPurchaseOrderDetail.orderNum){
          this.$modal.msgError(this.tblPurchaseReturnDetailList[i].productInfo.name+"的退货数量不能大于采购数量");
          return false;
        }
      }
      return true;
    },
    async getProductStock(scId, productId) {
      try {
        const response = await listStock({ scId, productId });
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取商品库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    //物料库存表数据
    getMaterialStockList(){
      listMaterialStock().then(response => {
        this.materialStockAllList=[]

        let list = response.rows;
        for (let i = 0; i < list.length; i++) {
          this.materialStockAllList.push(list[i].id)
        }
      });
    },

    //物料库存
    async getMaterialStock(scId, materialId) {
      try {
        const response = await listMaterialStock({ warehouseId:scId, materialId:materialId });
        const stock = response.rows[0];
        return stock;
      }catch (error) {
        console.error('获取物料库存失败:', error);
        return null; // 返回 null 表示获取失败
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购退单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchaseReturn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/PurchaseReturn/export', {
        ...this.queryParams
      }, `PurchaseReturn_${new Date().getTime()}.xlsx`)
    },

    // 查看按钮
    selectPurchaseReturn(row) {
      this.purchaseType=row.tblPurchaseReturnDetailList[0].purchaseType

      const id = row.id || this.ids
      getPurchaseReturn(id).then(response => {
        this.form = response.data;
        this.tblPurchaseReturnDetailList = response.data.tblPurchaseReturnDetailList;
        if (this.purchaseType==1){
          for (let i = 0; i < this.tblPurchaseReturnDetailList.length; i++) {
            let num=this.tblPurchaseReturnDetailList[i].material.materialType
            let name= num===1 ? "原材料" : num===2 ? "半成品" :num===3 ? "成品" : "辅料"
            this.tblPurchaseReturnDetailList[i].material.typeName=name
          }
        }
        this.open = true;
        this.title = "查看采购退货";
        this.giftNum=response.data.totalGiftNum;
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }
    },

    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='1';
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=new Date();
          updateReceiveSheet(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open = false;
            this.queryParams={}
            this.getList();
          });
        }
      });
    },
    //审批按钮
    async statusUpdate(row){
      this.getSupplierListId()

      this.purchaseType=row.tblPurchaseReturnDetailList[0].purchaseType

      const id = row.id || this.ids
      getPurchaseReturn(id).then(response => {
        this.form = response.data;
        this.tblPurchaseReturnDetailList = response.data.tblPurchaseReturnDetailList;
        if (this.purchaseType==1){
          for (let i = 0; i < this.tblPurchaseReturnDetailList.length; i++) {
            let num=this.tblPurchaseReturnDetailList[i].material.materialType
            let name= num===1 ? "原材料" : num===2 ? "半成品" :num===3 ? "成品" : "辅料"
            this.tblPurchaseReturnDetailList[i].material.typeName=name
          }
        }
        this.open = true;
        this.title = "审批采购订单";
      });

      if (row.status==0){
        this.statusColor = "rgb(100, 100, 100)";
      }else if (row.status==3){
        this.statusColor = "rgb(82, 196, 26)";
      }else {
        this.statusColor = "rgb(255, 0, 0)";
      }

      await this.getReceiveSheetList(this.form.purchaseOrderId)
      await this.selectReturnByOrderId(this.form.purchaseOrderId);
    },
  },beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="GYSYFK";    //供应商应付款
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(6,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(6,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
